import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_enjoy_plus/constants/index.dart';
import 'package:flutter_enjoy_plus/utils/toast.dart';
import 'package:geolocator/geolocator.dart';
import 'package:permission_handler/permission_handler.dart';

class LocationList extends StatefulWidget {
  const LocationList({super.key});

  @override
  State<LocationList> createState() => _LocationListState();
}

class _LocationListState extends State<LocationList> {
  String currentLocation = '';
  // 周边社区列表
  List<dynamic> aroundList = [];
  @override
  void initState() {
    super.initState();
    _getPermission();
  }
  // 获取位置权限
  _getPermission() async {
    PermissionStatus status = await Permission.location.request();
    if (status.isGranted) {
      PromptAction.showToast('允许请求位置');
      _getLocation();
    } else {
      PromptAction.showToast('拒绝请求位置');
    }
  }
  _getLocation() async {
    Position position = await Geolocator.getCurrentPosition();
    PromptAction.showToast('当前位置：纬度${position.latitude}, 经度${position.longitude}');
    _getAddress(position.longitude,position.latitude);
    _getAround(position.longitude,position.latitude);
  }
  _getAddress(double longitude,double latitude) async {
    Dio dio = Dio();
    final res = await dio.get(GlobalVariable.GAODE_baseUrl+HTTP_PATH.GAODE_POSITION,
      queryParameters: {
        'key': 'bd13e70f8f7c9e3640c08a4e6b5009ee',
        'location': '$longitude,$latitude',
      });
    if (res.data['status'] == '1') {
      setState(() {
        currentLocation = res.data['regeocode']['formatted_address'];
      });
    }
  }
  _getAround(double longitude,double latitude) async {
    Dio dio = Dio();
    final res = await dio.get(GlobalVariable.GAODE_baseUrl+HTTP_PATH.GAODE_AROUND,
      queryParameters: {
        'key': 'bd13e70f8f7c9e3640c08a4e6b5009ee',
        'location': '$longitude,$latitude',
        'keywords': '美食',
        'radius': 2000,
        'offset':10
      });
    if (res.data['status'] == '1') {
      setState(() {
        aroundList = res.data['pois'];
      });
    }
  }
  List<Widget> getAroundList() {
    return aroundList.map((item) {
      return Container(
          color: Colors.white,
          padding: const EdgeInsets.all(10),
          child: Row(
            children: [
              Expanded(child: Text(item['name'])),
              const Row(
                children: [
                  Icon(Icons.arrow_forward_ios,
                      size: 16, color: Colors.black),
                ],
              )
            ],
          ),
        );
    }).toList();
  }
  resetLocation(){
    _getAddress(121.492156,31.233462);
    _getAround(121.492156,31.233462);
  }

// bd13e70f8f7c9e3640c08a4e6b5009ee
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('选择社区'),
      ),
      body: ListView(
        padding: const EdgeInsets.all(10),
        children: [
          const Row(
            children: [
              Text(
                '当前地址',
                style: TextStyle(color: Colors.grey),
              )
            ],
          ),
          const SizedBox(height: 10),
          Container(
            color: Colors.white,
            padding: const EdgeInsets.all(10),
            child: Row(
              children: [
                Expanded(child: Text(currentLocation)),
                GestureDetector(
                  onTap: () {
                    resetLocation();
                  },
                  child: const Row(
                    children: [
                      Icon(Icons.location_searching_outlined, color: Colors.blue),
                      SizedBox(width: 2),
                      Text(
                        '重新定位',
                        style: TextStyle(color: Colors.blue),
                      ),
                    ],
                  )
                )
              ],
            ),
          ),
          const SizedBox(height: 10),
          const Row(
            children: [
              Text(
                '附近社区',
                style: TextStyle(color: Colors.grey),
              )
            ],
          ),
          const SizedBox(height: 10),
          ListView(
            shrinkWrap: true,
            physics: const NeverScrollableScrollPhysics(),
            children: getAroundList(),
          )
        ],
      ),
    );
  }
}